<template>
    <div class="white-box">
        <el-form ref="ruleNewsRef" :model="ruleNewsForm" :rules="ruleNews" label-width="120px">
            <el-form-item label="文章分类" prop="cate_id">
                <el-cascader
                    v-model="ruleNewsForm.cate_id"
                    :props="props"
                    :options="class_options"
                    placeholder="请选择文章分类"
                    :disabled="eid <= 9 && cid <= 2"
                />
            </el-form-item>
            <el-form-item label="文章标题" prop="title">
                <el-input v-model.trim="ruleNewsForm.title" clearable placeholder="请输入文章标题" :disabled="eid <= 9" />
            </el-form-item>
            <el-form-item label="封面图" prop="img_paths">
                <div class="img-box flexs-center" @click.stop="clickCover" v-if="ruleNewsForm.img_paths == ''">
                    <el-icon color="#999" size="26px">
                        <UploadFilled />
                    </el-icon>
                </div>
                <div class="img-selects" v-else>
                    <el-image class="img-selects__pic" :src="proxy.imgUrl + ruleNewsForm.img_paths + '!img_400'" :preview-src-list="srcList" fit="cover" />
                    <div class="img-del" @click.stop="delImg">
                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="文章内容" prop="title">
                <div class="editor-box" v-loading="videoLoading" element-loading-text="上传视频中，请耐心等待...">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
                    <Editor
                        style="height: 440px; overflow-y: hidden"
                        v-model="valueHtml"
                        :defaultConfig="editorConfig"
                        mode="default"
                        @onCreated="handleCreated"
                    />
                </div>
            </el-form-item>
            <el-form-item label="发布时间" prop="dates">
                <el-date-picker v-model="ruleNewsForm.dates" type="datetime" placeholder="请选择发布时间" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="排序" prop="sort" v-if="eid > 9">
                <el-input v-model.trim="ruleNewsForm.sort" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入排序" />
            </el-form-item>
            <el-form-item label="是否隐藏" prop="news_status" v-if="eid > 9">
                <el-switch
                    v-model="ruleNewsForm.news_status"
                    inline-prompt
                    size="large"
                    active-text="否"
                    inactive-text="是"
                    :active-value="0"
                    :inactive-value="1"
                />
            </el-form-item>
            <el-form-item label="状态" prop="audit" v-if="eid > 9">
                <el-switch
                    v-model="ruleNewsForm.audit"
                    inline-prompt
                    width="72px"
                    size="large"
                    active-text="发布"
                    inactive-text="待审核"
                    :active-value="1"
                    :inactive-value="0"
                />
            </el-form-item>
            <el-form-item>
                <div class="foot-btn flexs-center" style="margin-top: 30px">
                    <el-button type="primary" size="large" :loading="form_loading" @click="submitNewsForm(ruleNewsRef)">确认修改</el-button>
                </div>
            </el-form-item>
        </el-form>

        <!-- 图片库 -->
        <picture-library :show="showImg" :select_multiple="img_type == 1 ? false : true" @close="showImg = false" @select="selectImg"> </picture-library>

        <go-back />
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, shallowRef, reactive, onBeforeUnmount } from "vue"
import { useRouter, useRoute } from "vue-router"
import { UploadFilled, CloseBold } from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"
import PictureLibrary from "@components/PictureLibrary.vue"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

let eid = route.query.eid || ""
let cid = route.query.cid || ""

onMounted(() => {
    eid && getDetail()
})
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    insertFns.value = null
    if (editor == null) return
    editor.destroy()
})

const class_options = ref([])
// 配置级联选择参数
const props = ref({
    value: "cate_id",
    label: "title",
    children: "children",
})
function getDetail() {
    proxy.$axios
        .get("article/update", {
            params: {
                article_id: eid,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                class_options.value = result.cate_items

                ruleNewsForm.cate_id = result.detail.cate_id
                ruleNewsForm.title = result.detail.title
                ruleNewsForm.dates = result.detail.on_time_label
                ruleNewsForm.sort = result.detail.order_by
                ruleNewsForm.news_status = result.detail.hidden
                ruleNewsForm.audit = result.detail.audit
                if (result.detail && result.detail.thumb) {
                    ruleNewsForm.img_paths = result.detail.thumb
                    srcList.value.push(proxy.imgUrl + result.detail.thumb)
                }
                result.detail.content = result.detail.content.replace(/<img [^>]*src=['"]/g, `<img src="${proxy.imgUrl}`) // 往图片追加根域名和'/'
                valueHtml.value = result.detail.content.replace(/<source [^>]*src=['"]/g, `<source src="${proxy.imgUrl}`)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 添加
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Number} classType 弹窗类型，1是添加，2是编辑
 * @property {Array} ruleNewsRef 表单规则
 * @property {Object} ruleNewsForm  表单字段
 * @property {Object} ruleNews  表单提示
 * @property {Function} submitNewsForm 提交表单
 */
const form_loading = ref(false)
const ruleNewsRef = ref(null)
const ruleNewsForm = reactive({
    cate_id: "",
    title: "",
    dates: "",
    sort: "100",
    news_status: 0, // [0:显示,1:隐藏]
    audit: 1, // 0:待审核,1:已通过
    img_paths: "",
})
const ruleNews = reactive({
    cate_id: [{ required: true, message: "请选择文章分类", trigger: "change" }],
    title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
    img_paths: [{ required: true, message: "请选择封面图片", trigger: "blur" }],
    dates: [{ required: true, message: "请选择发布时间", trigger: "change" }],
    sort: [{ required: true, message: "请输入排序数字", trigger: "blur" }],
})
const submitNewsForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            let htmls = ""
            if (valueHtml.value) {
                htmls = valueHtml.value.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
            }

            let cid = ""
            cid = Array.isArray(ruleNewsForm.cate_id) ? ruleNewsForm.cate_id[ruleNewsForm.cate_id.length - 1] : ruleNewsForm.cate_id

            form_loading.value = true
            proxy.$axios
                .post("article/update", {
                    article_id: eid,
                    cate_id: cid,
                    title: ruleNewsForm.title,
                    thumb: ruleNewsForm.img_paths,
                    on_time: ruleNewsForm.dates,
                    order_by: ruleNewsForm.sort,
                    hidden: ruleNewsForm.news_status,
                    audit: ruleNewsForm.audit,
                    content: htmls,
                })
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "编辑成功！", type: "success" })
                        router.push("/News/NewsList")
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}

/**
 * 添加图片
 * @property {Boolean} showImg 显示图片库
 * @property {Number} img_type 1是上传封面，2是富文本上传
 * @property {Function} selectImg 选择图片
 */
const showImg = ref(false)
const img_type = ref(1)
const srcList = ref([])
const selectImg = (val) => {
    showImg.value = false
    if (img_type.value == 1) {
        ruleNewsForm.img_paths = val[0].photo
        srcList.value.push(proxy.imgUrl + val[0].photo)
    } else {
        for (let i = 0; i < val.length; i++) {
            insertFns.value(proxy.imgUrl + val[i].photo)
        }
    }
}
const delImg = () => {
    ruleNewsForm.img_paths = ""
    srcList.value = []
}
// 上传封面图
const clickCover = () => {
    img_type.value = 1
    showImg.value = true
}

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {String} valueHtml 输入内容
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const valueHtml = ref("") // 内容 HTML
const toolbarConfig = {
    // 排除不需要的菜单
    excludeKeys: ["insertLink", "insertImage", "editImage", "viewImageLink", "insertVideo", "emotion", "fullScreen"],
}
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
// 自定义上传图片
const insertFns = ref(null)
editorConfig.MENU_CONF["uploadImage"] = {
    // 自定义选择上传图片方式-可用于点击上传-图片库-选择图片插入
    customBrowseAndUpload(insertFn) {
        img_type.value = 2
        showImg.value = true
        insertFns.value = insertFn
    },
    // async customUpload(file, insertFn) {
    //     let data = new FormData()
    //     data.append("from", "album")
    //     data.append("image", file)
    //     proxy.$axios
    //         .post("upload/image", data)
    //         .then((res) => {
    //             if (res.data.code == 0) {
    //                 let url = proxy.imgUrl + res.data.data.path
    //                 insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
    //             } else {
    //                 proxy.$message({ message: res.data.msg, type: "error" })
    //             }
    //         })
    //         .catch((err) => {})
    // },
}
// 自定义上传视频
const videoLoading = ref(false)
editorConfig.MENU_CONF["uploadVideo"] = {
    async customUpload(file, insertFn) {
        videoLoading.value = true
        let data = new FormData()
        data.append("file", file)
        proxy.$axios
            .post("upload/video", data)
            .then((res) => {
                videoLoading.value = false
                if (res.data.code == 0) {
                    let url = proxy.imgUrl + res.data.data.path
                    insertFn(url) // 最后插入视频 insertFn(url poster)
                } else {
                    proxy.$message({ message: res.data.msg, type: "error" })
                }
            })
            .catch((err) => {
                videoLoading.value = false
            })
    },
}
</script>
<script>
export default {
    name: "NewsEdit",
}
</script>

<style lang="less" scoped>
.editor-box {
    border: 1px solid #ccc;
    border-radius: 2px;
}

:deep(.el-date-editor) {
    width: 320px !important;

    .el-input__wrapper {
        width: 320px;
    }
}

.prize-upload {
    :deep(.el-upload--picture-card) {
        width: 120px;
        height: 120px;
        line-height: 120px;
        margin-bottom: 20px;
    }

    :deep(.el-upload-list__item) {
        width: 120px;
        height: 120px;
    }
}
</style>
